package com.mfoyou.agent.web.controller.account;

import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.apache.http.conn.ConnectTimeoutException;
import org.mfoyou.agent.common.dao.domain.HuawuAgentInfo;
import org.mfoyou.agent.common.dao.domain.HuawuAgentStoreSetting;
import org.mfoyou.agent.common.dao.domain.HuawuAgentWxInfo;
import org.mfoyou.agent.common.dao.domain.HuawuAlipay;
import org.mfoyou.agent.common.dao.domain.HuawuNotice;
import org.mfoyou.agent.common.dao.domain.HuawuOrderLog;
import org.mfoyou.agent.common.dao.domain.HuawuServiceOrder;
import org.mfoyou.agent.common.dao.domain.HuawuUser;
import org.mfoyou.agent.common.dao.domain.HuawuWxPushModel;
import org.mfoyou.agent.common.dao.mfoyou.domain.MfoyouGoodsOrder;
import org.mfoyou.agent.common.entity.enums.OrderState;
import org.mfoyou.agent.common.entity.enums.OrderType;
import org.mfoyou.agent.common.inf.ICommon;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.common.inf.IOrder;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.common.DateUtils;
import org.mfoyou.agent.utils.common.HttpsUtils;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.ListObject;
import org.mfoyou.agent.utils.common.Logger;
import org.mfoyou.agent.utils.common.MfoyouEncrypt;
import org.mfoyou.agent.utils.json.JSONMaker;
import org.mfoyou.agent.utils.json.Json2Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.account.AccountService;
import com.mfoyou.agent.web.service.account.RunnerService;
import com.mfoyou.agent.web.service.order.GoodOrderService;
import com.mfoyou.agent.web.service.order.ServiceOrderService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;

@Path("/admin")
@Service
public class AdminService {

    private static final Logger logger = Logger.getLogger(AdminService.class);

    String supertoken = "wx:admin:usertoken:";

    @Autowired
    SessionService sessionService;

    @Autowired
    AccountService accountService;

    @Autowired
    ICommon iCommon;

    @Autowired
    RedisCacheManger redisCacheManger;

    @Autowired
    GoodOrderService goodOrderService;

    @Autowired
    IOrder iOrder;

    @Autowired
    ServiceOrderService serviceOrderService;

    @Autowired
    IIdentity iIdentity;

    @Autowired
    RunnerService runnerService;

    /**
     * 设置基本信息
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/setBaseInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> setBaseInfo(@Context HttpServletRequest request, String json) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        JSONObject json2MfoyouMap = Json2Object.json2JsonObject(json);
        String phone = json2MfoyouMap.getString("phone");
        String name = json2MfoyouMap.getString("name");
        String passWord = json2MfoyouMap.getString("password");
        Integer type = json2MfoyouMap.getInteger("type");
        Date time = json2MfoyouMap.getDate("endDate");
        String remark = json2MfoyouMap.getString("remark");
        //事务  没时间考虑，后期有时间再说
        HuawuUser huawuUser = new HuawuUser();
        huawuUser.setUserPhone(phone);
        huawuUser.setAgentId(0);
        huawuUser.setUserNickName(name);
        huawuUser.setUserPassword(passWord);
        huawuUser.setUserType(type);
        Integer userId = accountService.registUserV2(huawuUser);
        if (userId == null) {
            logger.info("userId is  null");
            return JsonRet.buildRet(-1);
        }
        if (userId < 0) {
            return JsonRet.buildRet(-2002);
        }
        huawuUser.setUserId(userId);
        HuawuAgentInfo huawuAgentInfo = new HuawuAgentInfo();
        huawuAgentInfo.setAgentId(userId);
        huawuAgentInfo.setAgentName(name);
        huawuAgentInfo.setAgentPhone(phone);
        huawuAgentInfo.setAgentUserName(name);
        huawuAgentInfo.setRemark(remark);
        huawuAgentInfo.setAgentEndTime(time);
        iCommon.addHuawuAgentInfo(huawuAgentInfo);
        HuawuAgentStoreSetting huawuAgentStoreSetting = new HuawuAgentStoreSetting();
        huawuAgentStoreSetting.setAgentId(userId);
        huawuAgentStoreSetting.setStoreUrl(MfoyouEncrypt.enCode(userId));
        huawuAgentStoreSetting.setServiceUrl(MfoyouEncrypt.enCode(userId));
        huawuAgentStoreSetting.setServiceName(name);
        huawuAgentStoreSetting.setStoreName(name);
        huawuAgentStoreSetting.setPhone(phone);
        huawuAgentStoreSetting.setStorePhone(phone);
        iCommon.addAgentStoreSetting(huawuAgentStoreSetting);
        return JsonRet.buildSuccRet(huawuUser);
    }

    /**
     * 更新服务商信息
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/updateRemark")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> updateRemark(@Context HttpServletRequest request, String json) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        JSONObject json2MfoyouMap = Json2Object.json2JsonObject(json);
        Integer agentId = json2MfoyouMap.getInteger("agentId");
        String remark = json2MfoyouMap.getString("remark");
        Integer type = json2MfoyouMap.getInteger("type");
        String password = json2MfoyouMap.getString("password");
        Date time = json2MfoyouMap.getDate("endDate");
        if (agentId == null) {
            return JsonRet.buildRet(-96);
        }
        int ret1 = 1;
        if (password != null || type != null) {
            HuawuUser huawuUser = new HuawuUser();
            huawuUser.setUserId(agentId);
            huawuUser.setUserPassword(password);
            huawuUser.setUserType(type);
            ret1 = accountService.modifyHuawuUser(huawuUser);
        }
        int ret2 = 1;
        if (remark != null || time != null) {
            HuawuAgentInfo huawuAgentInfo = new HuawuAgentInfo();
            huawuAgentInfo.setAgentId(agentId);
            huawuAgentInfo.setRemark(remark);
            huawuAgentInfo.setAgentEndTime(time);
            ret2 = iCommon.modifyAgentInfo(huawuAgentInfo);
        }
        return JsonRet.buildSuccRet(ret1 & ret2);
    }

    /**
     * 设置服务商微信信息
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/setWxInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> setWxInfo(@Context HttpServletRequest request, String json) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        //加事务  后来者优化
        JSONObject jsonObject = Json2Object.json2JsonObject(json);
        String mchid = jsonObject.getString("mchid");
        String pass = jsonObject.getString("pass");
        String path = jsonObject.getString("path");
        Integer userId = jsonObject.getInteger("userId");
        if (userId == null) {
            return JsonRet.buildRet(-96);
        }
        JSONArray jsonArray = jsonObject.getJSONArray("xcxs");
        if (jsonArray != null) {
            List<HuawuAgentWxInfo> list = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject xcx = jsonArray.getJSONObject(i);
                HuawuAgentWxInfo huawuAgentWxInfo = new HuawuAgentWxInfo();
                huawuAgentWxInfo.setXcxId(xcx.getString("appid"));
                huawuAgentWxInfo.setXcxSecret(xcx.getString("xcxSecret"));
                huawuAgentWxInfo.setAgentId(userId);
                huawuAgentWxInfo.setXcxType(xcx.getInteger("type"));
                huawuAgentWxInfo.setXcxName(xcx.getString("xcxName"));
                huawuAgentWxInfo.setXcxMchid(mchid);
                huawuAgentWxInfo.setXcxPayRediPath(path);
                huawuAgentWxInfo.setXcxPaySecret(pass);
                list.add(huawuAgentWxInfo);
            }
            iCommon.addWxInfos(list);
        } else if (mchid != null || pass != null || path != null) {
            HuawuAgentWxInfo huawuAgentWxInfo = new HuawuAgentWxInfo();
            huawuAgentWxInfo.setXcxMchid(mchid);
            huawuAgentWxInfo.setXcxPaySecret(pass);
            huawuAgentWxInfo.setXcxPayRediPath(path);
            iCommon.updateHuawuAgentWxInfoByAgentId(huawuAgentWxInfo, userId);
        }

        String aliappid = jsonObject.getString("aliappid");
        if (aliappid != null) {
            String aliprivateKey = jsonObject.getString("aliprivateKey");
            String publicKey = jsonObject.getString("publicKey");
            HuawuAlipay huawuAlipay = new HuawuAlipay();
            huawuAlipay.setAgentId(userId);
            huawuAlipay.setAlipayAppid(aliappid);
            huawuAlipay.setAlipayPrivateKey(aliprivateKey);
            huawuAlipay.setAlipayPublicKey(publicKey);
            iCommon.addAlipay(huawuAlipay);
        }

        JSONArray pushjsonArray = jsonObject.getJSONArray("wxpush");
        if (pushjsonArray != null) {
            List<HuawuWxPushModel> pushlist = new ArrayList<>();
            for (int i = 0; i < pushjsonArray.size(); i++) {
                JSONObject push = pushjsonArray.getJSONObject(i);
                HuawuWxPushModel huawuWxPushModel = new HuawuWxPushModel();
                huawuWxPushModel.setAgentId(userId);
                huawuWxPushModel.setModelId(push.getString("modelId"));
                huawuWxPushModel.setModelType(push.getInteger("modelType"));
                pushlist.add(huawuWxPushModel);
            }
            iCommon.addPushModel(pushlist);
        }
        return JsonRet.buildSuccRet(null);
    }

    /**
     * 获取服务商列表
     *
     * @param request
     * @param pageId
     * @param pageSize
     * @param key
     * @return
     */
    @GET
    @Path(value = "/getAgentList")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getAgentList(@Context HttpServletRequest request, @QueryParam("pageId") Integer pageId,
                                   @QueryParam("pageSize") Integer pageSize, @QueryParam("searchKey") String key) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        ArrayListObject<Map<String, Object>> agentList = iCommon.getAgentList(pageId, pageSize, key);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(agentList));
    }

    /**
     * 获取基本信息
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/getBaseInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getBaseInfo(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        Map<?, ?> agentByAgnetId = iCommon.getAgentByAgnetId(agentId);
        return JsonRet.buildSuccRet(agentByAgnetId);
    }

    /**
     * 获取服务商微信配置信息
     *
     * @param request
     * @param agentId 服务商id
     * @return
     */
    @GET
    @Path(value = "/getBaseWxInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getBaseWxInfo(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        Map<?, ?> agentByAgnetId = iCommon.getAgentWxInfoByAgnetId(agentId);
        return JsonRet.buildSuccRet(agentByAgnetId);
    }

    /**
     * 根据类型关键字查询服务商信息
     *
     * @param request
     * @param apptype
     * @param pageId
     * @param pageSize
     * @param key
     * @return
     */
    @GET
    @Path(value = "/getWxInfoByXcxTypeId")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getWxInfoByXcxTypeId(@Context HttpServletRequest request, @QueryParam("apptype") Integer apptype,
                                           @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize, @QueryParam("key") String key) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        Integer userId = null;
        if (key != null && Pattern.matches("[0-9]{11}", key)) {
            HuawuUser userInfoByPhoneV1 = accountService.userInfoByPhoneV1(key, 0);
            userId = userInfoByPhoneV1 == null ? null : userInfoByPhoneV1.getUserId();
            key = null;
        }
        ArrayListObject<?> agentByAgnetId = iCommon.getWxinfoByXcxType(apptype, pageId, pageSize, userId, key);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(agentByAgnetId));
    }

    /**
     * 获取服务商认证信息
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/getXcxAuditInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getXcxAuditInfo(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        List<Map<String, Object>> agentByAgnetId = iCommon.getWxinfo(agentId);
        return JsonRet.buildSuccRet(agentByAgnetId);
    }

    /**
     * 发布代码
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/release")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> release(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId
            , @QueryParam("appid") Integer appid) {
        if (agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        String postToAdmin = postToAdmin(huawuWxInfo.getXcxId(), "release", "{}", "post");
        JSONObject result = JSON.parseObject(postToAdmin);
        if (result.getIntValue("errcode") == 0) {
            iCommon.updateThirdPart(huawuWxInfo.getXcxId(), 1);
            return JsonRet.buildRet(0);
        }
        return JsonRet.buildFailRet(postToAdmin);
    }

    /**
     * 发布代码
     *
     * @param request
     * @param agentId
     * @return
     */
    @POST
    @Path(value = "/dealWithState")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> dealWithState(@Context HttpServletRequest request, String json) {
        ArrayList<JsonRet<?>> list = new ArrayList<>();
        logger.info(json);
        JSONObject parseObject = JSON.parseObject(json);
        String action = parseObject.getString("action");
        if (action.equals("submit")) {
            JSONArray jsonArray = parseObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                Integer agentId = jsonArray.getJSONObject(i).getInteger("agentId");
                Integer appid = jsonArray.getJSONObject(i).getInteger("appid");
                if (agentId == null || appid == null) {
                    list.add(JsonRet.buildFailRet("信息不全"));
                    continue;
                }
                list.add(submitToTencent(request, agentId, appid));
            }
        } else if (action.equals("check")) {
            JSONArray jsonArray = parseObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                Integer agentId = jsonArray.getJSONObject(i).getInteger("agentId");
                Integer appid = jsonArray.getJSONObject(i).getInteger("appid");
                if (agentId == null || appid == null) {
                    list.add(JsonRet.buildFailRet("信息不全"));
                    continue;
                }
                list.add(getLatestModel(request, agentId, appid));
            }
        } else if (action.equals("realse")) {
            JSONArray jsonArray = parseObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                Integer agentId = jsonArray.getJSONObject(i).getInteger("agentId");
                Integer appid = jsonArray.getJSONObject(i).getInteger("appid");
                if (agentId == null || appid == null) {
                    list.add(JsonRet.buildFailRet("信息不全"));
                    continue;
                }
                list.add(release(request, agentId, appid));
            }
        } else if (action.equals("upload")) {
            JSONArray jsonArray = parseObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                Integer agentId = jsonArray.getJSONObject(i).getInteger("agentId");
                Integer appid = jsonArray.getJSONObject(i).getInteger("appid");
                if (agentId == null || appid == null) {
                    list.add(JsonRet.buildFailRet("信息不全"));
                    continue;
                }
                list.add(pushCodeToTencent(request, jsonArray.getJSONObject(i).toJSONString()));
            }
        } else {
            return JsonRet.buildRet(-13);
        }
        return JsonRet.buildSuccRet(list);
    }

    /**
     * 提交审核
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/submitToTencent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> submitToTencent(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId
            , @QueryParam("appid") Integer appid) {
        if (agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        String address = iCommon.getAddressByappid(appid);
        if (address == null) {
            return JsonRet.buildFailRet("address未配置，呼叫大姐");
        }
        JSONObject category = getCategory(huawuWxInfo);
        if (category == null) {
            return JsonRet.buildFailRet("获取分类失败，联系陈龙");
        }
        category.put("title", "首页");
        category.put("tag", appid == 100 ? "外卖" : "跑腿");
        category.put("address", address);
        JSONObject jsonObject = new JSONObject();
        ArrayList<JSONObject> arrayList = new ArrayList<>();
        arrayList.add(category);
        jsonObject.put("item_list", arrayList);
        String postToAdmin = postToAdmin(huawuWxInfo.getXcxId(), "submit_audit", jsonObject.toJSONString(), "post");
        JSONObject result = JSON.parseObject(postToAdmin);
        if (result.getIntValue("errcode") == 0) {
            return JsonRet.buildRet(0);
        }
        return JsonRet.buildFailRet(postToAdmin);
    }

    /**
     * 获取设置
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/getLatestStateFromTencent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getLatestModel(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId
            , @QueryParam("appid") Integer appid) {
        if (agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        String postToAdmin = postToAdmin(huawuWxInfo.getXcxId(), "get_latest_auditstatus", null, "get");
        return JsonRet.buildFailRet(postToAdmin);
    }

    /**
     * 设置业务域名
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/setDomain")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> updateDomain(@Context HttpServletRequest request, String json) {
        JSONObject parseObject = JSON.parseObject(json);
        String domain = parseObject.getString("domain");
        Integer agentId = parseObject.getInteger("agentId");
        Integer appid = parseObject.getInteger("appid");
        if (domain == null || agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action", "add");
        jsonObject.put("requestdomain", new String[]{"https://api.udpt.cn", "https://restapi.amap.com"});
        jsonObject.put("uploaddomain", new String[]{"https://api.udpt.cn"});
        String postToAdmin = postToAdmin(huawuWxInfo.getXcxId(), "modify_domain", jsonObject.toJSONString(), "post");
        JSONObject result = JSON.parseObject(postToAdmin);
        if (result.getIntValue("errcode") != 0) {
            JsonRet.buildFailRet(postToAdmin);
        }
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("action", "add");
        jsonObject2.put("webviewdomain", new String[]{domain});
        postToAdmin(huawuWxInfo.getXcxId(), "setwebviewdomain", jsonObject2.toJSONString(), "post");
        return JsonRet.buildRet(0);
    }

    /**
     * 设置公告
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/setNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> setNotice(@Context HttpServletRequest request, String json) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        JSONObject parseObject = JSON.parseObject(json);
        String title = parseObject.getString("title");
        String content = parseObject.getString("content");
        Integer type = parseObject.getInteger("type");
        if (title == null || content == null || type == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuNotice huawuNotice = new HuawuNotice();
        huawuNotice.setTitle(title);
        huawuNotice.setContent(content);
        huawuNotice.setType(type);
        int ret = iCommon.addHuawuNotice(huawuNotice);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 设置公告
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/modifyNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> modifyNotice(@Context HttpServletRequest request, String json) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        JSONObject parseObject = JSON.parseObject(json);
        String title = parseObject.getString("title");
        String content = parseObject.getString("content");
        Integer type = parseObject.getInteger("type");
        Integer id = parseObject.getInteger("id");
        if ((title == null && content == null && type == null) || id == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuNotice huawuNotice = new HuawuNotice();
        huawuNotice.setId(id);
        huawuNotice.setTitle(title);
        huawuNotice.setContent(content);
        huawuNotice.setType(type);
        int ret = iCommon.updateNotice(huawuNotice);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 获取公告
     *
     * @param request
     * @param type
     * @param pageSize
     * @param pageId
     * @return
     */
    @GET
    @Path(value = "/getNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> modifyNotice(@Context HttpServletRequest request, @QueryParam("type") Integer type, @QueryParam("pageSize") Integer pageSize
            , @QueryParam("pageId") Integer pageId) {
        if (type == null) {
            return JsonRet.buildRet(-96);
        }
        ArrayListObject<?> notice = iCommon.getNotice(pageId, pageSize, type);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(notice));
    }

    /**
     * 获取单独公告
     *
     * @param request
     * @param id
     * @return
     */
    @GET
    @Path(value = "/getSingleNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getSingleNotice(@Context HttpServletRequest request, @QueryParam("id") Integer id) {
        if (id == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuNotice huawuNotice = iCommon.getSingleNotice(id);
        return JsonRet.buildSuccRet(huawuNotice);
    }

    /**
     * 删除公告
     *
     * @param request
     * @param id
     * @return
     */
    @GET
    @Path(value = "/deleteNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> deleteNotice(@Context HttpServletRequest request, @QueryParam("id") Integer id) {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        if (id == null) {
            return JsonRet.buildRet(-96);
        }
        int ret = iCommon.deleteNotice(id);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 上传代码
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "/pushCodeToTencent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> pushCodeToTencent(@Context HttpServletRequest request, String json) {
        JSONObject parseObject = JSON.parseObject(json);
        Integer template_id = parseObject.getInteger("template_id");
        Double versionId = parseObject.getDouble("versionId");
        Integer agentId = parseObject.getInteger("agentId");
        Integer appid = parseObject.getInteger("appid");
        if (agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        HuawuAgentWxInfo huawuWxInfoAuth = null;
        if (appid.intValue() == 101) {
            huawuWxInfoAuth = iCommon.getHuawuWxInfo(agentId, 200);
            if (huawuWxInfoAuth == null) {
                return JsonRet.buildFailRet("微信公众号未配置");
            }
        }
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        if (template_id == null || versionId == null) {
            HashMap<String, Object> modelId = iCommon.getModelId(huawuWxInfo.getXcxId(), appid);
            template_id = (Integer) modelId.get("appid_model_id");
            versionId = (Double) modelId.get("versionId");
            if (template_id == null || versionId == null) {
                return JsonRet.buildRet(-96);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("template_id", template_id);
        jsonObject.put("ext_json", makeExtJson(huawuWxInfo, appid == 101 ? huawuWxInfoAuth.getXcxId() : null, versionId + ""));
        jsonObject.put("user_version", "V" + versionId);
        String postToAdmin = postToAdmin(huawuWxInfo.getXcxId(), "commit", jsonObject.toJSONString(), "post");
        JSONObject result = JSON.parseObject(postToAdmin);
        if (result.getIntValue("errcode") == 0) {
            iCommon.increaseAppid(huawuWxInfo.getXcxId(), template_id, versionId + "");
            iCommon.updateThirdPart(huawuWxInfo.getXcxId(), 0);
            return JsonRet.buildRet(0);
        }
        return JsonRet.buildFailRet(postToAdmin);
    }

    /**
     * 获取推荐版本号
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "/getAdviceXcxModelId")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getXcxModelBy(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId
            , @QueryParam("appid") Integer appid) {
        if (agentId == null || appid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuAgentWxInfo huawuWxInfo = iCommon.getHuawuWxInfo(agentId, appid);
        if (huawuWxInfo == null) {
            return JsonRet.buildFailRet("微信未配置");
        }
        HashMap<String, Object> modelId = iCommon.getModelId(huawuWxInfo.getXcxId(), appid);
        return JsonRet.buildSuccRet(modelId);
    }

    /**
     * 创建extJson
     *
     * @param huawuWxInfo
     * @param huawuAuthId
     * @param version
     * @return
     */
    public String makeExtJson(HuawuAgentWxInfo huawuWxInfo, String huawuAuthId, String version) {
        JSONObject mainJson = new JSONObject();
        mainJson.put("extEnable", "true");
        mainJson.put("extAppid", huawuWxInfo.getXcxId());
        mainJson.put("directCommit", "false");
        JSONObject extJson = new JSONObject();
        extJson.put("name", "xmd_config");
        JSONObject merchantObject = new JSONObject();
        merchantObject.put("appName", huawuWxInfo.getXcxName());
        merchantObject.put("agentId", huawuWxInfo.getAgentId());
        merchantObject.put("agentStr", MfoyouEncrypt.enCode(huawuWxInfo.getAgentId()));
        merchantObject.put("appId", huawuWxInfo.getXcxId());
        merchantObject.put("authId", huawuAuthId);
        merchantObject.put("version", version);
        extJson.put("merchant", merchantObject);
        mainJson.put("ext", extJson);
        return mainJson.toJSONString();
    }

    /**
     * 推送消息到老平台验证
     *
     * @param huawuAgentWxInfo
     * @return
     */
    public JSONObject getCategory(HuawuAgentWxInfo huawuAgentWxInfo) {
        String postToAdmin = postToAdmin(huawuAgentWxInfo.getXcxId(), "get_category", null, "get");
        JSONObject parseObject = JSON.parseObject(postToAdmin);
        if (parseObject.getIntValue("errcode") != 0) {
            return null;
        }
        JSONArray jsonArray = parseObject.getJSONArray("category_list");
        if (jsonArray.size() == 0) {
            return null;
        }
        return jsonArray.getJSONObject(0);
    }

    /**
     * 推送消息到老平台验证
     *
     * @param appid
     * @param path
     * @param data
     * @param method
     * @return
     */
    public String postToAdmin(String appid, String path, String data, String method) {
        String token = redisCacheManger.getValue("wx:admin:usertoken");//硬加的
        String url = "http://api.mfoyou.com/wx/wxPost?token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", appid);
        jsonObject.put("path", path);
        jsonObject.put("data", data);
        jsonObject.put("method", method);
        try {
            String postJson = HttpsUtils.postJson(url, jsonObject.toJSONString());
            logger.info(postJson);
            return postJson;
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询订单列表
     *
     * @param request
     * @param response
     * @param ssdate
     * @param eedate
     * @param pageid
     * @param pageSize
     * @param orderNumber
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/cloud/orderList")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getCloudOrderList(@Context HttpServletRequest request,
                                        @Context HttpServletResponse response,
                                        @QueryParam("sdate") String ssdate, @QueryParam("edate") String eedate,
                                        @QueryParam("pageId") Integer pageid, @QueryParam("pageSize") Integer pageSize,
                                        @QueryParam("orderNum") String orderNumber) throws ParseException {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        MfoyouGoodsOrder order = new MfoyouGoodsOrder();
        order.setOrderNumber(orderNumber);
        Date startDate = ssdate == null ? null : DateUtils.date_sdf.parse(ssdate);
        Date endDate = eedate == null ? null : DateUtils.date_sdf.parse(DateUtils.formatAddDate(eedate, "yyyy-MM-dd", 1));
        ArrayListObject<MfoyouGoodsOrder> goodsOrderList = goodOrderService.getGoodsOrderList(order, startDate, endDate,
                pageid, pageSize, null, 0);
        for (MfoyouGoodsOrder goodsOrder : goodsOrderList) {
            HuawuAgentInfo agentInfo = iIdentity.getAgentInfo(goodsOrder.getAreaAgentId());
            goodsOrder.setAgentUserName(agentInfo.getAgentUserName());
        }
        return JsonRet.buildSuccRet(ListObject.BulidListObject(goodsOrderList));
    }

    /**
     * 获取服务商下的订单列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param orderNumber
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/agent/orderList")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getAgentOrderlist(
            @Context HttpServletRequest request,
            @Context HttpServletResponse response,
            @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
            @QueryParam("orderNum") String orderNumber, @QueryParam("sdate") String start,
            @QueryParam("edate") String end) throws ParseException {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderNumber(orderNumber);
        Date startDate = start == null ? null : DateUtils.date_sdf.parse(start);
        Date endDate = end == null ? null : DateUtils.date_sdf.parse(DateUtils.formatAddDate(end, "yyyy-MM-dd", 1));
        ArrayListObject<HuawuServiceOrder> listObject = iOrder.getServiceOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, null, null);
        for (HuawuServiceOrder huawuServiceOrder : listObject) {
            HuawuAgentInfo agentInfo = iIdentity.getAgentInfo(huawuServiceOrder.getAgentId());
            huawuServiceOrder.setAgentUserName(agentInfo.getAgentUserName());
        }
        return JsonRet.buildSuccRet(ListObject.BulidListObject(serviceOrderService.attachWorkerInfo(listObject, null)));
    }

    /**
     * 获取一个订单的信息
     *
     * @param request
     * @param response
     * @param orderId
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/info")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> orderInfo(@Context HttpServletRequest request,
                                @Context HttpServletResponse response,
                                @QueryParam("orderId") Integer orderId) throws ParseException {
        if (!sessionService.checkOldSession(request)) {
            return JsonRet.buildRet(-18);
        }
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderId(orderId);
        ArrayListObject<HuawuServiceOrder> listObject =
                serviceOrderService.getServiceOrderList(mfoyouServiceOrder, null, null, null, null, null, null);
        if (listObject.size() == 1) {
            JSONObject ret = JSONMaker.AttachSubJsonString(listObject.get(0), "servicePayType");
            List<HuawuOrderLog> status = iOrder.getOrderLog(orderId, OrderType.serviceOrder.getValue());
            Date start = null;
            Date finsh = null;
            for (HuawuOrderLog mfoyouOrderLog : status) {
                if (mfoyouOrderLog.getOrderLogState() == OrderState.emServiceStart.getValue()) {
                    start = mfoyouOrderLog.getOrderLogTime();
                }
                if (mfoyouOrderLog.getOrderLogState() == OrderState.emServiceRunerFinsh.getValue()) {
                    finsh = mfoyouOrderLog.getOrderLogTime();
                }
            }
            if (finsh != null && start != null) {
                long value = finsh.getTime() - start.getTime();
                ret.put("taskDuration", value / 1000);
            }
            ret.put("flowList", JSON.toJSON(status));
            Integer wokerId = listObject.get(0).getServiceOrderReceiveUser();
            if (wokerId != null) {
                ret.putAll(runnerService.getWorkKeysInfo(wokerId,
                        new String[]{"userName", "userHeadUrl", "userPhone", "workerCommentCount", "workerName", "workerPhone", "workerStar", "userNickName",
                                "workerOrderCount", "workerServiceDistance", "workerLong", "workerLat"}));
            }
            return JsonRet.buildSuccRet(ret);
        }
        return JsonRet.buildRet(-98);
    }
}
